package com.education.online.controller;


import com.education.common.config.BusinessException;
import com.education.common.config.CommonErrorCode;
import com.education.common.pojo.OUserMaster;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.DateUtil;
import com.education.common.utils.FileGetSizeUtil;
import com.education.online.feign.UserFeign;
import com.education.online.pojo.*;
import com.education.online.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 备课共享资源表
 *
 * @date 2020-06-04 15:17:49
 */
@Api(tags = {"PC--备课共享资源表"})
@RestController
@RequestMapping("/online/opreparesources")
public class OPrepaResourcesController {

    @Autowired
    private OPrepaResourcesService oPrepaResourcesService;

    @Autowired
    private OLabelService oLabelService;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private OPrepaTypeService oPrepaTypeService;

    @Autowired
    private OCatalogMenuService oCatalogMenuService;

    @Autowired
    private OPrepaLabelService oPrepaLabelService;

    @Autowired
    private OPrapaUserBuyService oPrapaUserBuyService;

    @Autowired
    private OUserMasterService oUserMasterService;


    @ApiOperation(value = "备课共享资源购买", httpMethod = "POST")
    @PostMapping("/courseBuy")
    @Transactional
    public ApiReturnObject courseBuy(Integer prapaResId, Integer userId) throws BusinessException {
        if (userId == null || prapaResId == null) {
//            return new ApiReturnObject("203", "failure", "参数缺失");
            throw new BusinessException(CommonErrorCode.E_200101);
        }
        //查询该课件信息 课件的userID是上传用户的id
        OPrepaResources resources = selectResources(prapaResId, userId);
        //查询该课程是否购买
        isBuy(userId, resources);

        //查询并修改用户达人币数量
        updateMaster(userId, resources);

        //添加购买课程
        insertBuy(userId, resources);

        //达人币明细
        insertMaster(userId, resources);

        return new ApiReturnObject("200", "success", "购买成功");
    }

    /**
     * 查询并修改用户达人币数量
     *
     * @param userId
     * @param resources
     */
    private void updateMaster(Integer userId, OPrepaResources resources) {
        Map<String, Object> map = userFeign.findByPCUserId(userId);
        if (map == null) {
            throw new BusinessException(CommonErrorCode.E_200103);//用户不存在
        }
        //查询上传用户
        Map<String, Object> map1 = userFeign.findByPCUserId(resources.getUserId());
        //修改用户达人币总数
        if (map.get("price").toString() == null || "".equals(map.get("price").toString())) {
            //return new ApiReturnObject("201", "failure", "达人币为空 请充值");
            throw new BusinessException(CommonErrorCode.E_300103);
        }

        //Integer price = Integer.parseInt(map.get("price").toString()) - resources.getPrice();
        BigDecimal price = new BigDecimal(map.get("price").toString()).subtract(new BigDecimal(resources.getPrice()));
        //if (price < 0) {
        if (price.compareTo(BigDecimal.ZERO) < 0) {
            //return new ApiReturnObject("202", "failure", "达人币不足 请充值");
            throw new BusinessException(CommonErrorCode.E_300103);
        }
        //修改购买用户的达人币数量
        //userFeign.updateByPCUserId(userId, price);
        userFeign.updateByPCUserId(userId, price);

        //修改上传用户达人币数量
        //userFeign.updateByPCUserId(resources.getUserId(), Integer.parseInt(map1.get("price").toString()) + resources.getPrice());
        userFeign.updateByPCUserId(resources.getUserId(), new BigDecimal(map1.get("price").toString()).add(new BigDecimal(resources.getPrice())));
    }

    /**
     * 查询该课程是否购买
     *
     * @param userId
     * @param resources
     */
    private void isBuy(Integer userId, OPrepaResources resources) {
        OPrapaUserBuy userBuy1 = new OPrapaUserBuy();
        userBuy1.setPrapaId(resources.getId());
        userBuy1.setUserId(userId);//当前用户购买
        List<OPrapaUserBuy> buyList = oPrapaUserBuyService.selectOPrapaUserBuyList(userBuy1);
        if (buyList.size() > 0) {
//            return new ApiReturnObject("204", "failure", "该用户已购买该课程 不能重复购买");
            throw new BusinessException(CommonErrorCode.E_300102);
        }
    }

    /**
     * 查询该课件信息 课件的userID是上传用户的id
     *
     * @param prapaResId
     * @param userId
     * @return
     */
    private OPrepaResources selectResources(Integer prapaResId, Integer userId) {
        OPrepaResources resources = oPrepaResourcesService.selectOPrepaResourcesById(prapaResId);
        if (userId == resources.getUserId()) {
//            return new ApiReturnObject("203", "failure", "不能自己购买自己的课件");
            throw new BusinessException(CommonErrorCode.E_300101);
        }
        return resources;
    }

    /**
     * 添加到购买课程
     *
     * @param userId
     * @param resources
     */
    private void insertBuy(Integer userId, OPrepaResources resources) {
        OPrapaUserBuy userBuy = new OPrapaUserBuy();
        userBuy.setPrapaId(resources.getId());
        userBuy.setUserId(userId);//当前用户购买
        userBuy.setCreateTime(new Date());
        oPrapaUserBuyService.insertOPrapaUserBuy(userBuy);
    }

    /**
     * 达人币明细
     *
     * @param userId
     * @param resources
     */
    private void insertMaster(Integer userId, OPrepaResources resources) {
        //添加购买用户的达人币明细
        OUserMaster oUserMaster1 = new OUserMaster();
        oUserMaster1.setContext(resources.getRName());//课程名称
        oUserMaster1.setUserId(userId);
        oUserMaster1.setPeople(0 - resources.getPrice());//课程价格
        oUserMaster1.setCreatetime(new Date());
        oUserMasterService.insertOUserMaster(oUserMaster1);
        //添加上传用户达人币明细
        OUserMaster oUserMaster = new OUserMaster();
        oUserMaster.setContext(resources.getRName());//课程名称
        oUserMaster.setUserId(resources.getUserId());
        oUserMaster.setPeople(resources.getPrice());//课程价格
        oUserMaster.setCreatetime(new Date());
        oUserMasterService.insertOUserMaster(oUserMaster);
    }


    @ApiOperation(value = "上传备课资源", httpMethod = "POST")
    @PostMapping("/uploadCourse")
    public ApiReturnObject uploadCourse(OPrepaResources oPrepaResources) {
        oPrepaResources.setCreateTime(new Date());
        oPrepaResources.setRSize(FileGetSizeUtil.getQiNiuUrl2(oPrepaResources.getRUrl()));
        oPrepaResourcesService.insertOPrepaResources(oPrepaResources);
        List<Integer> list = Arrays.asList(oPrepaResources.getIds());
        for (Integer s : list) {
            OPrepaLabel label = new OPrepaLabel();
            label.setPerpaId(oPrepaResources.getId());
            label.setLabelId(s);
            oPrepaLabelService.insertOPrepaLabel(label);
        }
        return new ApiReturnObject("200", "success", "");
    }

    @ApiOperation(value = "课程筛选", httpMethod = "GET")
    @GetMapping("/screening")
    public ApiReturnObject screening(Integer menuId, Integer typeId) {
        List<OPrepaResources> resourcesList = oPrepaResourcesService.selectOPrepaResourcesByPrepaIdAndTypeId(menuId, typeId);
        getDetails(resourcesList);
        return new ApiReturnObject("200", "success", resourcesList);
    }

    @ApiOperation(value = "查询全部资源", httpMethod = "GET")
    @GetMapping("/selectList")
    public ApiReturnObject selectList(Integer prepaId, Integer pageNum, Integer pageSize) {
        if (pageNum != null && pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        OPrepaResources resources = new OPrepaResources();
        resources.setId(prepaId);
        List<OPrepaResources> prepaResourcesList = oPrepaResourcesService.selectOPrepaResourcesList(resources);
        getDetails(prepaResourcesList);
        PageInfo<OPrepaResources> pageInfo = new PageInfo<>(prepaResourcesList);
        return new ApiReturnObject("200", "success", pageInfo);
    }

    @ApiOperation(value = "搜索", httpMethod = "GET")
    @GetMapping("/search")
    public ApiReturnObject search(String name) {
        List<OPrepaResources> prepaResourcesList = oPrepaResourcesService.selectOPrepaResourcesByName(name);
        getDetails(prepaResourcesList);
        return new ApiReturnObject("200", "success", prepaResourcesList);
    }

    @ApiOperation(value = "我的上传", httpMethod = "GET")
    @GetMapping("/MyUpload")
    public ApiReturnObject myUpload(Integer userId) {
        OPrepaResources oPrepaResources = new OPrepaResources();
        oPrepaResources.setUserId(userId);
        List<OPrepaResources> resourcesList = oPrepaResourcesService.selectOPrepaResourcesList(oPrepaResources);
        getDetails(resourcesList);
        return new ApiReturnObject("200", "success", resourcesList.size(), resourcesList);
    }

    @ApiOperation(value = "我的购买", httpMethod = "GET")
    @GetMapping("/MyPrapaBuy")
    public ApiReturnObject myPrapaBuy(Integer userId) {
        List<OPrepaResources> resourcesList = oPrepaResourcesService.selectOPrepaResourcesByUserId(userId);
        getDetails(resourcesList);
        return new ApiReturnObject("200", "success", resourcesList);
    }

    /**
     * 查询共享资源详情
     *
     * @param resourcesList
     */
    private void getDetails(List<OPrepaResources> resourcesList) {
        for (OPrepaResources oPrepaResources : resourcesList) {
            //查询标签
            List<OLabel> labelList = oLabelService.selectOLabelByPerpaId(oPrepaResources.getPrepaId());
            oPrepaResources.setOLabelList(labelList);
            //处理时间
            oPrepaResources.setTime(DateUtil.dateFormat(oPrepaResources.getCreateTime()));
            //查询课件由谁发布
            Map<String, Object> map = userFeign.findByPCUserId(oPrepaResources.getUserId());
            if (map != null) {
                oPrepaResources.setRelName(map.get("name").toString());
                oPrepaResources.setImage(map.get("image").toString());
            } else {
                oPrepaResources.setRelName("游客");
                oPrepaResources.setImage("1589614399509.jpg");
            }
            //查询该发布者发布课件总数
            Integer integer = oPrepaResourcesService.selectCount(oPrepaResources.getUserId());
            oPrepaResources.setPreoaCount(integer);
            //查询媒体类型
            OPrepaType type = oPrepaTypeService.selectOPrepaTypeById(oPrepaResources.getTypeId());
            oPrepaResources.setType(type.getTypeName());
            //查询专业类型
            OCatalogMenu oCatalogMenu = oCatalogMenuService.selectOCatalogMenuById(oPrepaResources.getPrepaId());
            oPrepaResources.setMenuName(oCatalogMenu.getMenuName());
        }
    }


}
